package com.chj.kmp.test;

public class CodeTest02_Manacher {
	public static char[] manacherString(String str) {
		char[] ss = str.toCharArray();
		char[] res = new char[2 * str.length() + 1];
		int index = 0;
		for (int i = 0; i < res.length; i++) {
			res[i] = (i & 1) == 0 ? '#' : ss[index++];
		}

		return res;
	}

	public static int maxLcpsLength(String str) {
		if (str == null || str.length() == 0) {
			return 0;
		}

		char[] ss = manacherString(str);
		int[] pArr = new int[ss.length];

		int mid = 0;
		int right = 0;
		int max = Integer.MIN_VALUE;

		for (int i = 0; i < ss.length; i++) {
			if (i >= right) {
				while (i + pArr[i] < ss.length && i - pArr[i] > -1) {
					if (ss[i + pArr[i]] == ss[i - pArr[i]]) {
						pArr[i]++;
					} else {
						break;
					}
				}

				if (i + pArr[i] > right) {
					right = i + pArr[i];
					mid = i;
				}

			}

			if (i < right) {
				int ii = pArr[2 * mid - i];
				int ir = right - i;

				if (ii > ir) {
					pArr[i] = ir;
				} else if (ii < ir) {
					pArr[i] = ii;
				} else {
					while (i + pArr[i] < ss.length && i - pArr[i] > -1) {
						if (ss[i + pArr[i]] == ss[i - pArr[i]]) {
							pArr[i]++;
						} else {
							break;
						}
					}

					if (i + pArr[i] > right) {
						right = i + pArr[i];
						mid = i;
					}
				}
			}

			max = Math.max(max, pArr[i]);
		}

		return max - 1;

	}

	public static void main(String[] args) {
		String str1 = "abc1234321ab";
		System.out.println(maxLcpsLength(str1));

		String str2 = "ddabbade";
		System.out.println(maxLcpsLength(str2));

		String str3 = "abcd12399321";
		System.out.println(maxLcpsLength(str3));
	}
}
